/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package utils;

import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author banhbaochay
 */
public class Utils {

    /**
     * Filter information from web's response form: name=a&value=b&..., then
     * save information to Map<String, String> object
     * @param response Response from web has form name=a&value=b&...
     * @return Map object have form: key = name and value = a...
     */
    public static Map<String, String> getTokenRespone(String response) {
        Map<String, String> map = new HashMap<String, String>();
        StringTokenizer tokenByAndMark = new StringTokenizer(response, "&");
        while (tokenByAndMark.hasMoreTokens()) {
            String[] tokenByEqualMark = tokenByAndMark.nextToken().split("=");
            map.put(tokenByEqualMark[0], tokenByEqualMark[1]);
        }
        return map;
    }

    /**
     * Get string which is saved in clipboard
     * @return String is saved in clipboard
     * @throws Exception if can't get from clipboard
     */
    public static String getClipboard() throws Exception {
        String result = null;
        Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
        Transferable t = clipboard.getContents(null);
        if (t != null && t.isDataFlavorSupported(DataFlavor.stringFlavor)) {
            result = (String) t.getTransferData(DataFlavor.stringFlavor);
        }
        return result;
    }

    /**
     * Save String to clipboard
     * @param str whatever String to save to clipboard
     */
    public static void setClipboard(String str) {
        StringSelection ss = new StringSelection(str);
        Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null);
    }

    /**
     * Get information between tag html. Example: get abcdef from <data>abcdef
     * </data>
     * @param input String has tag in
     * @param tag Tag has information in which you want to get
     * @return Information between tag
     */
    public static String getFromTag(String input, String tag) {
        return getFromTag(input, tag, 0);
    }

    public static String getFromTag(String input, String tag, int fromIndex) {
        String data = null;
        String startTag = "<" + tag + ">";
        String endTag = "</" + tag + ">";
        int startPos = input.indexOf(startTag, fromIndex);
        int endPos = input.indexOf(endTag, fromIndex);
        data = input.substring(startPos + startTag.length(), endPos);
        return data;
    }

    /**
     * Get all albums 's name from getAlbumInfo method
     * @param input reponse String from getAlbumInfo method
     * @return List of albums 's name
     */
    public static Map<String, HashMap<String, String>> getAlbumsMap(String response) {
        Map<String, HashMap<String, String>> albumsMap = new
                LinkedHashMap<String, HashMap<String, String>>();
        String searchName = "<album name=\"";
        String searchCount = "photo_count=\"";
        int startPos = 0;
        int offset = 0;
        while ((startPos = response.indexOf(searchName, offset)) != -1) {
            offset = startPos + searchName.length();
            int endPos = response.indexOf("\"", offset);
            String albumName = response.substring(offset, endPos);
            HashMap<String, String> albumInfo = new HashMap<String, String>();
            int countStartPos = response.indexOf(searchCount, offset);
            String photo_count = response.substring(countStartPos + searchCount.length(),
                    response.indexOf("\"", countStartPos + searchCount.length()));
            albumInfo.put("photo_count", photo_count);
            albumsMap.put(albumName, albumInfo);
        }
        return albumsMap;
    }

    /**
     * Get only file name of file, minus extension. Example get 'name' from
     * 'name.ext'
     * @param fileName file name with extension
     * @return file name without extension
     */
    public static String getFileNameWithoutExtension(String fileName) {
        String fileNameWithoutExtension = null;
        if (fileName.matches(".*\\..*")) {
            fileNameWithoutExtension = fileName.substring(0, fileName.indexOf("."));
        } else {
            fileNameWithoutExtension = fileName;
        }
        return fileNameWithoutExtension;
    }

    /**
     * Get browser you have in your OS. Only use in Linux
     * @return full path to browser. Example: /usr/bin/firefox
     */
    public static String getBrowsePathLinux() {
        String cmd = null;
        String[] browsers = {"firefox", "google-chrome", "opera", "epiphany",
            "konqueror", "conkeror", "midori", "kazehakase"};
        for (String browse : browsers) {
            try {
                Process p = Runtime.getRuntime().exec(new String[]{"which", browse});
                Thread.sleep(20);
                if (p.exitValue() == 0) {
                    BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
                    cmd = in.readLine();
                    break;
                }
            } catch (Exception ex) {
                Logger.getLogger(Utils.class.getName()).log(Level.SEVERE, null, ex);
                continue;
            }
        }
        return (cmd != null) ? cmd : "nobrowser";
    }
}
